package com.llkj.common.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.jakewharton.rxbinding2.view.RxView;
import com.llkj.common.R;
import com.llkj.common.base.app.BaseApp;
import com.llkj.common.base.delegate.IActivity;
import com.llkj.common.exception.ApiException;
import com.llkj.common.mvp.BasePresenter;
import com.llkj.common.mvp.IView;
import com.llkj.common.util.LoadDialogUtil;
import com.llkj.common.widget.titlebar.TitleBar;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.yokeyword.fragmentation.SupportActivityDelegate;

/**
 * author: zhu.px
 * e-mail: 1271901673@qq.com
 * time  : 2018/4/18
 * desc  :
 */
public abstract class BaseActivity<P extends BasePresenter> extends SupportActivity implements TitleBar.Delegate
        , IActivity, IView {

    final SupportActivityDelegate mDelegate = new SupportActivityDelegate(this);
    protected Context mContext;
    @Inject
    @Nullable
    protected P mPresenter;
    protected TitleBar titleBar;
    protected ImmersionBar immersionBar;
    private Unbinder unbinder;
    private CompositeDisposable mCompositeDisposable;

    @Override
    public void showLoadingDialog(String title) {
        LoadDialogUtil.showLoading(mContext);
    }

    @Override
    public void hideLoadingDialog() {
        LoadDialogUtil.hideLoading();
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void showMessage(int resId) {
        ToastUtils.showShort(resId);
    }

    @Override
    public void showErrorException(ApiException e) {
        ToastUtils.showShort(e.getMessage());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void showRefreshLoading() {

    }

    /**
     * 是否把状态栏字体及图标颜色设置为深色
     *
     * @return
     */
    protected boolean isDarkMode() {
        return true;
    }

    /**
     * 通过Class跳转界面
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }

    /**
     * 含有Bundle通过Class跳转界面
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        KeyboardUtils.hideSoftInput(this);
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null)
            intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        KeyboardUtils.hideSoftInput(this);
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 设置点击事件，并防止重复点击
     *
     * @param view
     * @param consumer
     */
    protected void setOnClick(View view, Consumer consumer) {
        RxView.clicks(view).throttleFirst(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(consumer);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActivityComponent(BaseApp.getInstance().getAppComponent());
        mDelegate.onCreate(savedInstanceState);
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
        if (getLayoutResId() != 0) {
            setContentView(getLayoutResId());
            unbinder = ButterKnife.bind(this);
        }
        titleBar = findViewById(R.id.title_bar);
        if (titleBar != null) {
            titleBar.setDelegate(this);
        }
        mContext = this;
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }
        if (isSetStatusBarAlpha()) {
            immersionBar = ImmersionBar.with(this);
            immersionBar.init();
            if (titleBar != null) {
                immersionBar.titleBar(titleBar);
            }
//            if (titleBar != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                titleBar.getLayoutParams().height = ConvertUtils.dp2px(45) + BarUtils.getStatusBarHeight();
//                titleBar.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0);
//            }
        }
        beforeInitView(savedInstanceState);
        initView();
        initData();
        initListener();
    }

    @Override
    public void onDestroy() {
        mDelegate.onDestroy();
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (immersionBar != null) {
            immersionBar.destroy();
        }
        unDispose();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        KeyBoardUtil.handleAutoCloseKeyboard(isAutoCloseKeyboard(), getCurrentFocus(), ev, this);
        return super.dispatchTouchEvent(ev);
    }

    void unDispose() {
        if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
    }

    protected boolean isSetStatusBarAlpha() {
        return true;
    }

    protected void beforeInitView(Bundle savedInstanceState) {
    }

    /**
     * 点击非 EditText 时，是否自动关闭键盘
     *
     * @return
     */
    protected boolean isAutoCloseKeyboard() {
        return true;
    }

    @Override
    public void onClickLeftCtv() {
        this.finish();
    }

    @Override
    public void onClickTitleCtv() {

    }

    @Override
    public void onClickRightCtv() {
    }

    @Override
    public void onClickRightSecondaryCtv() {

    }

    protected void addDispose(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void finish() {
        super.finish();
        KeyboardUtils.hideSoftInput(this);
    }
}
